package com.school.dao;

import com.school.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 用户DAO
 */
@Repository
public class UserDao {
    
    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    
    /**
     * 插入用户
     */
    public Long insert(User user) {
        String sql = "INSERT INTO tb_user (username, password, real_name, phone, status) " +
                "VALUES (:username, :password, :realName, :phone, :status)";
        
        MapSqlParameterSource params = new MapSqlParameterSource()
                .addValue("username", user.getUsername())
                .addValue("password", user.getPassword())
                .addValue("realName", user.getRealName())
                .addValue("phone", user.getPhone())
                .addValue("status", user.getStatus());
        
        KeyHolder keyHolder = new GeneratedKeyHolder();
        namedParameterJdbcTemplate.update(sql, params, keyHolder);
        return keyHolder.getKey().longValue();
    }
    
    /**
     * 更新用户
     */
    public int update(User user) {
        String sql = "UPDATE tb_user SET real_name = :realName, phone = :phone, status = :status WHERE id = :id";
        
        MapSqlParameterSource params = new MapSqlParameterSource()
                .addValue("id", user.getId())
                .addValue("realName", user.getRealName())
                .addValue("phone", user.getPhone())
                .addValue("status", user.getStatus());
        
        return namedParameterJdbcTemplate.update(sql, params);
    }
    
    /**
     * 根据用户名查询
     */
    public User findByUsername(String username) {
        String sql = "SELECT * FROM tb_user WHERE username = :username";
        MapSqlParameterSource params = new MapSqlParameterSource("username", username);
        List<User> list = namedParameterJdbcTemplate.query(sql, params, 
                (rs, rowNum) -> {
                    User u = new User();
                    u.setId(rs.getLong("id"));
                    u.setUsername(rs.getString("username"));
                    u.setPassword(rs.getString("password"));
                    u.setRealName(rs.getString("real_name"));
                    u.setPhone(rs.getString("phone"));
                    u.setStatus(rs.getInt("status"));
                    u.setCreateTime(rs.getTimestamp("create_time"));
                    u.setUpdateTime(rs.getTimestamp("update_time"));
                    return u;
                });
        return list.isEmpty() ? null : list.get(0);
    }
}


